<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2017/1/10
 * Time: 11:28
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
	die('error');
}

if (!defined('API_ROOT_PATH')) {
	define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
/**
 * @return MysqliDb
 */
function init_db()
{
	$db = new MysqliDb ([
		'host' => MYSQLDB,
		'username' => MYSQLDB_USER,
		'password' => MYSQLDB_PWD,
		'db' => MYSQLDB_DATABASE,
		'port' => 3306,
		'prefix' => 'au_',
		'charset' => 'utf8'
	]);
	return $db;
}
$db = init_db();
$bc_id = 0;
$lastId = 0;

//TODO 获取已完成的 过户信息
while (true){
	$list = $db->where('result',2)->where('transfer_id',$lastId,'>')->get('transfer_log',2000);
	if(empty($list)) {
		logUtil('处理完成');
		die();
	}
	foreach ($list as $key => $value){

		$orderId = $value['order_id'];
		$procedureInfo = getProcedureInfoByOrderId($orderId);
		if(!empty($procedureInfo)){ //如果手续信息已经存在了，就不在插入
			$lastId = $value['transfer_id'];
			continue;
		}

		$orderInfo = getOrderInfoByOrderId($orderId);
		$carId = $orderInfo['car_id'];
		$carInfo = getCarReportByCarId($carId);
		$carSource =  $carInfo['car_source'];
		if($carSource == 2){
			$lastId = $value['transfer_id'];
			continue;
		}

		$empId = $value['emp_id'];
		$lastUpdate = $value['last_update'];
		$empInfo = getEmployeeInfoByEmpId($empId);
		$empName  = $empInfo['real_name'];


		$data = [
			'order_id' => $orderId,
			'car_id' => $carId,
			'sid' => $value['sid'],
			'emp_id' => $empId,
			'emp_name' => $empName,
			'created_time' => $value['last_update'],
			'upload_time' => $value['last_update'],
			'upload_status' => 1,
		];
		$result = insertProcedures($data);
		if($result){
			logUtil('拍单：'.$orderId.'插入手续信息成功！');
		}
		$lastId = $value['transfer_id'];
	}
}

// 4s 车源添加手续信息
function insertProcedures($data){
	global $db;
	$result = $db->insert('procedures',$data);
	if(!$result){
		echo $db->getLastQuery();
		logUtil('拍单'.$data['order_id'].'插入手续信息失败!');
		die();
	}
	return $result;
}


//根据用户编号得到用户信息
function getEmployeeInfoByEmpId($empId){
	global $db;
	$data = $db->where('emp_id',$empId)->getOne('employee');
	return $data;
}

//根据车源号，得到报告信息
function getOrderInfoByOrderId($orderId){
	global $db;
	$orderInfo = $db->where('order_id',$orderId)->getOne('order');
	return $orderInfo;
}


function getCarReportByCarId($carId){
	global $db;
	$carInfo = $db->where('car_id',$carId)->getOne('cars');
	return $carInfo;
}

function getProcedureInfoByOrderId($orderId){
	global $db;
	$procedureInfo = $db->where('order_id',$orderId)->getOne('procedures');
	return $procedureInfo;
}